package fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.utils.StorageUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import co.yeye.test.Constance;
import co.yeye.test.ImageBrowser;
import co.yeye.test.MainActivity;
import co.yeye.test.R;
import listadapter.DiscoveryItemAdapter;
import models.DiscoveryObject;
import models.UserObject;

/**
 * Created by yeye on 15/2/18.
 */
public class DiscoveryFragment extends Fragment implements DiscoveryItemAdapter.onClickPicListener,
        NetworkAlert.setAlertDialog,DiscoveryItemAdapter.onBottomBtnListener{
    SwipeRefreshLayout layout;
    Button tittle;
    ListView list;
    ImageLoader imageLoader;
    DisplayImageOptions options;
    DiscoveryItemAdapter discoveryItemAdapter;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");   // 日期格式
    boolean isOnListBottom=false;       // 是否在列表底部

    private int page=1;     // 当前的页数

    public static DiscoveryFragment newInstance(){
        DiscoveryFragment fragment  = new DiscoveryFragment();
        return fragment;
    }

    public DiscoveryFragment(){

    }

    // 刷新图像适配器的用户信息，以配置adapter的底部按钮
    public void refreshAdapter(){
        discoveryItemAdapter.getUserCode();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.discovery_fragment_layout, container, false);
        setPullListener(rootView);
        list.setAdapter(discoveryItemAdapter);
        //Toast.makeText(getActivity().getBaseContext(),"from onCreatView",Toast.LENGTH_SHORT).show();
        // 获取网络状态
        int networkState = MainActivity.getInstance().getNetState();
        if(networkState==Constance.NETWORK_INVALID)
            setTittle(getResources().getString(R.string.network_invalid),
                    getResources().getColor(R.color.red), 0);
        //else
        //refreshDiscovery(true,true,false);
        return rootView;
    }

    /**
     * 网络变更通知
     */
    public void networkChanged(int state){
        // 先判断是否获取了tittle
        boolean isNull = tittle==null ? true : false;
        if(state==Constance.NETWORK_INVALID){
            if(!isNull)
                setTittle(getResources().getString(R.string.network_invalid),
                        getResources().getColor(R.color.red),0);
        }
        else {
            if(!isNull)
                tittle.setVisibility(View.GONE);
            NetworkAlert networkAlert = new NetworkAlert(this, state);
            networkAlert.start();
        }
    }

    @Override
    public void execute() {
        refreshDiscovery(true, true, false);
    }

    @Override
    public void onAttach(Activity activity) {
        imageLoaderInit();
        discoveryItemAdapter = new DiscoveryItemAdapter(MainActivity.getInstance(),imageLoader,options);
        // 注册按键监听器
        discoveryItemAdapter.setOnClickPicListener(this);
        discoveryItemAdapter.setOnBottomBtnListener(this);
        super.onAttach(activity);
    }

    private void setPullListener(View view){
        layout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        tittle = (Button) view.findViewById(R.id.refresh_text);
        tittle.setVisibility(View.GONE);

        layout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);

        list = (ListView) view.findViewById(R.id.listview);

        list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到底部
                        if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1)) {
                            // 避免底部最后一个选项的时候多次刷新
                            if(!isOnListBottom) {
                                if(MainActivity.getInstance().getNetState()==Constance.NETWORK_INVALID) {
                                    setTittle(getResources().getString(R.string.network_invalid),
                                            getResources().getColor(R.color.red), 0);
                                    layout.setRefreshing(false);
                                    return;
                                }
                                else
                                    refreshDiscovery(false, false, false);
                            }
                            isOnListBottom=true;
                        }
                        else
                            isOnListBottom=false;
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(MainActivity.getInstance().getNetState()==Constance.NETWORK_INVALID) {
                    setTittle(getResources().getString(R.string.network_invalid),
                            getResources().getColor(R.color.red), 0);
                    layout.setRefreshing(false);
                    return;
                }
                setTittle("正在刷新", Color.parseColor("#6495ed"),2000);
                // 获取用户信息
                //final UserObject userObject = MainActivity.getInstance().getUser();
                refreshDiscovery(true,false,true);
                isOnListBottom=false;
                // text
                //layout.setRefreshing(false);
            }
        });
    }

    /**
     * 刷新发现列表
     * @param isRefreshOnTop 是否为顶部刷新
     * @param isRestore 是否为本地读取
     * @param isNotify 是否通知用户
     */
    private void refreshDiscovery(final boolean isRefreshOnTop , final boolean isRestore ,
                                  final boolean isNotify ){
        // 查询服务器信息
        AVQuery<AVObject> query = new AVQuery<AVObject>("Discovery");
        //query.whereEqualTo("userCode", userObject.getUser_code());
        //if(isRestore)
        //    query.setLimit(Constance.SINGLE_REQUEST_ITEM_NUM);
        //else
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.setLimit(Constance.SINGLE_REQUEST_ITEM_NUM);
        if(!isRefreshOnTop)
            query.setSkip(Constance.SINGLE_REQUEST_ITEM_NUM * page++);
        else
            page=1;
        query.orderByDescending("createdAt");
        query.include("relation_user");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> avObjects, AVException e) {
                if(e==null){
                    if(avObjects.size()<=0){
                        setTittle("无更多消息",Color.parseColor("#cc0002"),2000);
                        layout.setRefreshing(false);
                        return;
                    }
                    // 刷新信息到列表内
                    // 开始构造，保存到ArrayList中
                    ArrayList<DiscoveryObject> objectArrayList = new ArrayList<DiscoveryObject>();
                    for(int i=0;i<avObjects.size();i++){
                        DiscoveryObject discoveryObject = new DiscoveryObject();
                        // 尝试使用关联的AVUser
                        AVUser avUser = avObjects.get(i).getAVUser("relation_user");
                        discoveryObject.setUser_name(avUser.getString("username"));
                        discoveryObject.setUser_img_url(avUser.getAVFile("user_img").getUrl());
                        //discoveryObject.setUser_name(avObjects.get(i).getString("user_name"));
                        //discoveryObject.setUser_img_url(avObjects.get(i).getString("user_img_url"));
                        discoveryObject.setContent(avObjects.get(i).getString("content"));
                        discoveryObject.setDate(simpleDateFormat.format(avObjects.get(i).getCreatedAt()));
                        //discoveryObject.setDate(avObjects.get(i).getCreatedAt().toString());
                        //discoveryObject.setDate("2015.2.18");
                        //int imagesNum = avObjects.get(i).getInt("imagesNum");
                        // 写入图像uri信息
                        ArrayList<String> imgUris = new ArrayList<String>();
                        ArrayList<String> imgUrisOrigin = new ArrayList<String>();
                        for(int j=0;j<9;j++){
                            AVFile imgFile = avObjects.get(i).getAVFile("image"+String.valueOf(j+1));
                            if(imgFile==null)
                                break;
                            imgUris.add(imgFile.getThumbnailUrl(false,300,300));
                            imgUrisOrigin.add(imgFile.getUrl());
                        }
                        discoveryObject.setImg_list(imgUris);
                        discoveryObject.setImg_list_origin(imgUrisOrigin);
                        discoveryObject.setCode(avObjects.get(i).getString("userCode"));
                        discoveryObject.setAvObject(avObjects.get(i));
                        objectArrayList.add(discoveryObject);
                    }
                    // 顶部刷新，则只需要刷新前面的数据即可
                    if(isRefreshOnTop)
                        discoveryItemAdapter.setDiscoveryObjectList(objectArrayList);
                    // 滑动到底部刷新，需要继续加载剩下的项目
                    else
                        discoveryItemAdapter.addDiscoveryObjectList(objectArrayList);
                    //list.setAdapter(discoveryItemAdapter);
                    discoveryItemAdapter.notifyDataSetChanged();
                    //list.notifyAll();
                    layout.setRefreshing(false);
                    if(isNotify)
                        setTittle("刷新完成", Color.parseColor("#6495ed"),1000);
                    return;
                }
                else {
                    //Toast.makeText(getActivity().getBaseContext(),e.toString(), Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                    return;
                }
            }
        });
    }

    private void imageLoaderInit(){
        File cacheDir = StorageUtils.getOwnCacheDirectory(getActivity().getBaseContext(), "imageloader/Cache");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(getActivity().getBaseContext())
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .discCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径
                .build();//开始构建
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);//全局初始化此配置

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.color.gray) //设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.ic_launcher)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.ic_launcher)  //设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)						// 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)							// 设置下载的图片是否缓存在SD卡中
                //.resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
                //.displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
                .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
                .build();//构建完成
    }

    /**
     * 配置顶部的按钮
     */
    private void setTittle( String text , int color , int time ){
        tittle.setText(text);
        tittle.setBackgroundColor(color);
        tittle.setVisibility(View.VISIBLE);

        if(time!=0) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tittle.setVisibility(View.GONE);
                }
            }, time);
        }
    }

    @Override
    public void picClick(DiscoveryObject obj, int picNum) {
        ArrayList<String> url = new ArrayList<String>();
        url = obj.getImg_list_origin();
        Intent intent = new Intent(getActivity(), ImageBrowser.class);
        intent.putStringArrayListExtra("urls",url);
        intent.putExtra("num",picNum-1);
        startActivity(intent);
    }

    @Override
    public void bottomBtnClick(final DiscoveryObject obj,int button, int position) {
        // 点赞
        if(button==Constance.DISCOVERY_ITEM_ZHAN){
            setTittle("功能尚未开放",getResources().getColor(R.color.red),2000);
        }
        // 删除
        else if(button==Constance.DISCOVERY_ITEM_DELETE){
            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                    .setTitle("确认删除")
                    .setMessage("删除成功后将无法恢复该条发现记录，请谨慎操作。")
                    .setNegativeButton("取消",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .setPositiveButton("确定",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            obj.getAvObject().deleteInBackground(new DeleteCallback() {
                                @Override
                                public void done(AVException e) {
                                    setTittle("删除成功",getResources().getColor(R.color.green),2000);
                                    refreshDiscovery(true,false,false);
                                }
                            });
                        }
                    })
                    .show();
        }
    }
}
